<template>
  <el-menu
      :default-active="activeMenu"
      class="el-menu-vertical"
      :collapse="isCollapse"
      :unique-opened="true"
      router
      @select="handleSelect"
  >
    <template v-for="menu in menuList" :key="menu.id">
      <el-sub-menu v-if="menu.children && menu.children.length" :index="menu.path">
        <template #title>
          <el-icon><component :is="menu.icon || 'Menu'" /></el-icon>
          <span>{{ menu.name }}</span>
        </template>
        <el-menu-item
            v-for="child in menu.children"
            :key="child.id"
            :index="child.path"
        >
          <el-icon><component :is="child.icon || 'Menu'" /></el-icon>
          <span>{{ child.name }}</span>
        </el-menu-item>
      </el-sub-menu>
      <el-menu-item v-else :index="menu.path">
        <el-icon><component :is="menu.icon || 'Menu'" /></el-icon>
        <span>{{ menu.name }}</span>
      </el-menu-item>
    </template>
  </el-menu>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import axios from 'axios'

const props = defineProps({
  isCollapse: {
    type: Boolean,
    default: false
  }
})

const route = useRoute()
const menuList = ref([])

const activeMenu = computed(() => {
  const { path } = route
  return path
})

const fetchMenuByRole = async () => {
  try {
    // 这里应该根据当前用户的角色ID获取菜单
    // 简化处理，直接获取所有菜单
    const response = await axios.get('api/menu/menu/tree')
    menuList.value = response.data
  } catch (error) {
    console.error('获取菜单失败', error)
  }
}

const handleSelect = (index) => {
  console.log('菜单选中:', index)
}

onMounted(() => {
  fetchMenuByRole()
})
</script>

<style>
.el-menu-vertical:not(.el-menu--collapse) {
  width: 220px;
  min-height: 100vh;
}
</style>